package org.je.image;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;

/**
 * @author fanyifeng
 */
public abstract class FlipCanvas extends Canvas
{
	private final boolean	needWatchSpeed;
	private int				_w;
	private int				_h;

	/**
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @param watchSpeed
	 */
	public FlipCanvas(int x, int y, int w, int h, boolean watchSpeed) {
		setBounds(x ,y ,w ,h);
		this._w = w;
		this._h = h;
		this.needWatchSpeed = watchSpeed;
		this.setIgnoreRepaint(true);
	}

	public int w() {
		return _w;
	}

	public int h() {
		return _h;
	}

	private long	t1;

	public void flipDraw() {
		if (needWatchSpeed) {
			t1 = System.nanoTime();
		}
		BufferStrategy bs = getBufferStrategy();

		Graphics g = bs.getDrawGraphics();
		draw2D((Graphics2D)g);
		g.dispose();
		if (bs.contentsLost() == false) {
			bs.show();
		}
		Toolkit.getDefaultToolkit().sync();
		if (needWatchSpeed) {
			onWatch(t1 ,t1 ,System.nanoTime());
		}
	}

	/**
	 * @param g
	 */
	public abstract void draw2D(Graphics2D g);

	/**
	 * t1 : paint start, t1 paint buffer end, t3: paint canvas end
	 * 
	 * @param t1
	 * @param t2
	 * @param t3
	 */
	public abstract void onWatch(long t1, long t2, long t3);

	private static final long	serialVersionUID	= 1L;
}
